let httpError = require('http-errors');
let config = require('../config');
let cors = require('cors');
let logger = require('morgan');
let express = require('express');

module.exports = (app) => {
    // cors跨域
    app.use(cors({
        origin: config.whitelist,
        methods: ['GET', 'POST'],
        alloweHeaders: ['Conten-Type', 'Authorization'],
    }));
    // 日志
    app.use(logger('tiny'));
    // express基本配置 request数据解析
    app.use(express.json());
    app.use(express.urlencoded({extended: false}));
    // 扩展response方法
    app.use(function (req, res, next) {
        res.httpError = function (status) {
            let err = httpError(status);
            return res.json({
                code: -1,
                status: err.status,
                msg: err.message,
            });
        };
        res.jsonFail = function (msg) {
            return res.json({
                code: 0,
                msg: msg,
            });
        };
        res.jsonSuccess = function (data, msg = null) {
            return res.json({
                code: 1,
                data: data,
                msg: msg,
            });
        };
        next();
    });

    // 注册路由
    require('./router.lib')(app);

    // 404
    app.use(function (req, res, next) {
        next(httpError(404));
    });
    // HttpError
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.json({
            code: -1,
            status: err.status,
            msg: err.message,
        });
    });
};
